#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""按照不同模式读取表格

"""
import xlrd
import xlwt
from Base import Base


class PoetryReadExcel(Base):
    def __init__(self):
        super(PoetryReadExcel, self).__init__()
        self.msg = ""
        self.error_msg = ""
        self.question_msg = ""
        self.question_error_msg = ""
        # 申请对象加载
        self.excel_to_poetry_list()

    @staticmethod
    def instance():
        global inst
        try:
            inst
        except:
            inst = PoetryReadExcel()
        return inst

    # 从Excel表格中读取所有当前诗词库中要加载的诗词
    def excel_to_poetry_list(self):
        poetrys = []
        ex_file = xlrd.open_workbook(self.cfg['path']['poetry_file_path'] + '/'
                                     + self.cfg['poetry_file']['poetry_file_name'])
        sheet = ex_file.sheet_by_name(self.cfg['poetry_file']['sheet_poetrys_name'])
        is_get = sheet.col_values(0)
        title_first = sheet.col_values(1)
        title_second = sheet.col_values(2)
        author = sheet.col_values(3)
        contents = sheet.col_values(4)

        for i in range(1, title_first.__len__()):
            if title_second[i] == "":
                title_second[i] = "no"
            poetry = [title_first[i], title_second[i], author[i]]
            filename = title_first[i] + "_" + title_second[i] + "_" + author[i]
            if is_get[i] != "Y":
                self.msg = self.msg + "\n" + "诗词【" + filename + "】没有加载。"
                continue
            contents_list = contents[i].split("\n")
            if len(contents_list) % 2 == 1:
                self.error_msg = self.error_msg + "\n" + "[error]诗词【" + filename + "】内容行数为奇数，请修改后再添加。"
                continue
            for item in contents_list:
                poetry.append(item)
            poetrys.append(poetry)
        return poetrys

    # 按照列表读取Excel 对于长短不一者去掉空值
    def get_many_short_long_cols(self, file_name, sheet_name):
        cols_dict = {}
        ex_file = xlrd.open_workbook(file_name)
        sheet = ex_file.sheet_by_name(sheet_name)
        title_list = sheet.row_values(0)
        for i in range(0, len(title_list)):
            word_list = sheet.col_values(i)
            word_list.remove(word_list[0])
            while '' in word_list:
                word_list.remove('')
            for j in range(0, len(word_list)):
                if isinstance(word_list[j], float):
                    word_list[j] = str(int(word_list[j]))
            cols_dict[title_list[i]] = word_list
        return cols_dict

    # 按照列表读取Excel， 每列读取长度一致
    def get_many_cols(self, file_name, sheet_name):
        cols_dict = {}
        ex_file = xlrd.open_workbook(file_name)
        sheet = ex_file.sheet_by_name(sheet_name)
        title_list = sheet.row_values(0)
        for i in range(0, len(title_list)):
            word_list = sheet.col_values(i)
            word_list.remove(word_list[0])
            for j in range(0, len(word_list)):
                if isinstance(word_list[j], float):
                    word_list[j] = str(int(word_list[j]))
            cols_dict[title_list[i]] = word_list
        return cols_dict

    # 在Excel中只读一列
    def get_col(self, sheet_name):
        ex_file = xlrd.open_workbook(self.cfg['path']['poetry_file_path'] + '/'
                                     + self.cfg['poetry_file']['poetry_file_name'])
        sheet = ex_file.sheet_by_name(sheet_name)
        return sheet.col_values(0)

    # 将有相同key的字典的list写入到Excel表格中
    def write_by_dict_list(self, data_list):
        """
        将有相同key的字典的list写入到Excel表格中
        :param data_list: 要写入的数据
        :return:
        """
        filename_question = '诗词题目_' + self.now + '.xls'
        ex_write = xlwt.Workbook(encoding='utf-8')
        sheet = ex_write.add_sheet('诗词题目')
        for i in range(0, len(data_list)):
            j = 0
            for key in data_list[0].keys():
                sheet.write(i, j, data_list[i][key])
                j = j + 1
        ex_write.save(self.cfg['path']['word_path'] + '\\' + filename_question)
        return filename_question
